package com.lungle.warmdiary.app.view.wallet.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.exception.ApiErrorHelper;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseFragmentInterface;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.AlipayAccount;
import com.lungle.warmdiary.app.utils.CountDownTimerUtil;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AccountCenterFragment extends BaseFragment {
    private static final String ACCOUNT_CENTER_SCREEN = "account center screen";
    public static final String ARGS_ACCOUNT = "account";
    private AlipayAccount mAccount;
    private FragmentControl mControl;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mAccount = (AlipayAccount) getArguments().getSerializable(ARGS_ACCOUNT);

        if (mAccount == null) {
            mControl = new UnbindViewExecutor();
        } else {
            mControl = new BindedViewExecutor();
        }
        View view = inflater.inflate(getLayoutId(), container, false);
        initView(view);

        return view;
    }


    @Override
    public void initView(View view) {
        mControl.initView(view);
    }

    @Override
    public void initData() {
        mControl.initData();
    }

    @Override
    public void onClick(View v) {
        mControl.onClick(v);
    }

    @Override
    protected int getLayoutId() {
        return mControl.getLayoutId();

    }


    @Override
    public void onResume() {
        super.onResume();
        hasBindAlipay();
        MobclickAgent.onPageStart(ACCOUNT_CENTER_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(ACCOUNT_CENTER_SCREEN);
        MobclickAgent.onPause(getActivity());

    }

    private void hasBindAlipay() {
        showWaitDialog();
        ApiFactory.getUserApi().getAliPay().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<AlipayAccount>>(getActivity()) {
                    @Override
                    public void onNext(Result<AlipayAccount> alipayAccountResult) {
                        super.onNext(alipayAccountResult);
                        mAccount = alipayAccountResult.getData();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();

                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                    }
                });
    }

    interface FragmentControl extends BaseFragmentInterface, View.OnClickListener {
        int getLayoutId();
    }

    //已经绑定支付宝了
    class BindedViewExecutor implements FragmentControl {

        private TextView mTvAccount;
        private EditText mEtCapture;
        private Button mBtnCapture;


        @Override
        public void initView(View view) {
            Button btnUnbind = (Button) view.findViewById(R.id.btn_unbind);
            mBtnCapture = (Button) view.findViewById(R.id.btn_captcha);

            btnUnbind.setOnClickListener(this);
            mBtnCapture.setOnClickListener(this);

            mTvAccount = (TextView) view.findViewById(R.id.tv_account_type);
            mTvAccount.setText(mAccount.getAccount());
            mEtCapture = (EditText) view.findViewById(R.id.et_capture);
            timer = CountDownTimerUtil.create(mBtnCapture);
        }

        @Override
        public void initData() {

        }

        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.btn_captcha:
                    String cellphone = AppContext.getInstance().getLoginUser().getCellphone();
                    if (!TDevice.hasInternet()) {
                        AppContext.showToast("无网络");
                        return;
                    }
                    showWaitDialog();
                    getCapture(cellphone);
                    break;
                case R.id.btn_unbind:
                    String capture = mEtCapture.getText().toString();
                    if (prepareCapture(capture)) {
                        unbind(mAccount.getId());
                    } else {
                        AppContext.showToast("输入验证码");
                    }
                    break;
            }


        }


        CountDownTimer timer ;

//        CountDownTimer timer = new CountDownTimer(60000, 1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//                mBtnCapture.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
//                mBtnCapture.setText(millisUntilFinished / 1000 + "秒后\n重新获取");
//                mBtnCapture.setClickable(true);
//                mBtnCapture.setEnabled(false);
//            }
//
//            @Override
//            public void onFinish() {
//                mBtnCapture.setClickable(true);
//                mBtnCapture.setEnabled(true);
//                mBtnCapture.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
//                mBtnCapture.setText("获取验证码");
//            }
//        };

        private boolean prepareCapture(String phone) {
            if (TextUtils.isEmpty(phone)) {
                AppContext.showToast("输入验证码");
                return false;
            }

            return true;

        }


        private void getCapture(String phone) {
            ApiFactory.getBaseApi().getCapture(phone, 2).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<Result>() {
                        @Override
                        public void onCompleted() {
                            hideWaitDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            if (e instanceof ApiException) {
                                ApiErrorHelper.showErrorDetail(((ApiException) e).getExtendErrorMsg());
                            }
                            hideWaitDialog();
                        }

                        @Override
                        public void onNext(Result result) {
                            timer.start();

                        }
                    });
        }

        private void unbind(String id) {
            showWaitDialog();
            ApiFactory.getUserApi().deleteAlipay(id).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseSubscriber<Result>(getActivity()) {
                        @Override
                        public void onNext(Result result) {
                            super.onNext(result);
                        }

                        @Override
                        public void onCompleted() {
                            super.onCompleted();
                            AppContext.showToast("解绑成功");
                            getActivity().finish();
                        }
                    });
        }

        @Override
        public int getLayoutId() {
            return R.layout.fragment_unbind_account;
        }
    }

    //未绑定支付包
    class UnbindViewExecutor implements FragmentControl {

        @Override
        public void initView(View view) {
            Button btnBind = (Button) view.findViewById(R.id.btn_bind_now);
            btnBind.setOnClickListener(this);
        }

        @Override
        public void initData() {

        }

        @Override
        public void onClick(View v) {
            getActivity().finish();
            UIHelper.showBindAccount(getActivity());
        }

        @Override
        public int getLayoutId() {
            return R.layout.fragment_account_center;
        }
    }


}
